/* eslint-disable prefer-promise-reject-errors */
/* eslint-disable consistent-return */
/* eslint-disable no-async-promise-executor */
import Taro from '@tarojs/taro'
import { generateUUID, crypto, base64 } from '@pier88health/p8h-common'
import api from '@API'
import DBConfig from '@CONFIG/DBConfig';
global.ossToken = {}

const OSS_FOLDER_MAP = {
  CareChat: 'static/img/carechat/',
  Consultation: 'static/img/consultation/',
  CareUser: 'static/img/careusers',
  Audio: 'audio/',
  CaseHistory: 'patient/',
}
const aliOssSignature = (aky, expiration) => {
  const policyText = {
    expiration: expiration || '2022-06-01T12:00:00.000Z',
    conditions: [
      ['content-length-range', 0, 10485760000]
    ]
  };
  const policy = base64.encode(JSON.stringify(policyText));
  const bytes = crypto.HMAC(crypto.SHA1, policy, aky, { asBytes: true });
  const signature = crypto.bytesToBase64(bytes);
  return {
    policy,
    signature
  }
}

const isOSSTokenExpired = () => Date.now() >= new Date(global.ossToken.Expiration).getTime() + 30 * 1000

const getPrivateUrl = async (type, folderId, name) => {
  try {
    const FilePath = `/${OSS_FOLDER_MAP[type]}${folderId}/${name}`;
    const result = await api.getSignatureUrl({ FilePath });
    return result?.data;
  } catch (error) {
    console.log('get private url error', error)
    return ''
  }
}

const getOssToken = () => new Promise(async resolve => {
  if (global.ossToken.SecurityToken && !isOSSTokenExpired()) {
    return resolve(Object.assign(global.ossToken, { isNewToken: false }))
  }
  const data = await api.requestOssToken()
  resolve(Object.assign(data, { isNewToken: true }))
})

const uploadFile = async ({
  path, type, folderId = '', staticName = '', staticExt = '', showProgress = false, isPrivate = false
}) => new Promise(async (resolve, reject) => {
  getOssToken().then(tokenRes => {
    global.ossToken = tokenRes
    const aliOss = aliOssSignature(tokenRes.AccessKeySecret, tokenRes.Expiration)
    const name = staticName || generateUUID()
    const ext = staticExt || path.substring(path.lastIndexOf('.') + 1, path.length);
    const fileName = `${OSS_FOLDER_MAP[type]}${folderId}/${name}${ext ? `.${ext}` : ''}`;
    const ossUrl = isPrivate ? DBConfig.privateOssUrl : DBConfig.ossUrl
    const uploadTask = Taro.uploadFile({
      // eslint-disable-next-line
      url: ossUrl, //上传的路径
      filePath: path,
      name: 'file',
      formData: {
        name: path,
        policy: aliOss.policy,
        signature: aliOss.signature,
        key: fileName, // 上传图片的名字和路径（默认路径根目录，自定义目录：xxx/xxx.png）
        OSSAccessKeyId: tokenRes.AccessKeyId,
        'x-oss-security-token': tokenRes.SecurityToken,
        success_action_status: '200'
      },
      success(res) {
        if (res.statusCode !== 200) {
          return reject('上传失败')
        }
        resolve({ id: folderId, name, ext })
      },
      fail({ errMsg }) {
        reject(errMsg)
      }
    })
    showProgress && uploadTask.progress(res => {
      const { progress } = res
      Taro.showLoading({
        title: `${progress}%`,
        mask: true,
      })
      if (progress >= 100) {
        Taro.hideLoading()
      }
      // console.log('上传进度', res.progress)
    })
  })
    .catch(error => {
      reject(error)
    })
})

export {
  OSS_FOLDER_MAP,
  uploadFile,
  getPrivateUrl
}
